<?php


namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\LinkstokenService;
use App\Services\MiniappService;
use App\Services\OutputService;
use App\Services\IpService;
use App\Services\DeviceService;
use App\Services\HtmlossService;
use App\Services\LinkapiService;
use App\Services\KefuService;
use App\Models\Linkslists;
use App\Models\Linksrecord;
use App\Models\Linkslistsminapps;
use App\Models\Linkslistssetting;
use App\Jobs\Miniappdisable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Log,Exception;

class LinksapiController extends Controller
{
    public function urlSchemeGenerate(Request $request)
    {
        $links_id = $request->links_id;
        $record_id = $request->record_id;
        $linkMiniappStatus = Cache::get("link_mini_".$links_id);
        if(empty($linkMiniappStatus)) {
            // 获取外链当前是否为公用
            $linksInfo = Linkslists::getLinkMiniappStatus($links_id);
            if (empty($linksInfo)) return OutputService::error("链接不存在!");
            $linkMiniappStatus = ["miniapp_status"=>$linksInfo->miniapp_status,"platfrom_type"=>$linksInfo->platfrom_type,"miniapp_type"=>$linksInfo->miniapp_type,"appid"=>$linksInfo->appid,"end_time"=>$linksInfo->end_time,"limit_pv"=>$linksInfo->limit_pv];
            Cache::put("link_mini_".$links_id, $linkMiniappStatus, 7200);
        }
        if ($linkMiniappStatus["end_time"] <= time()) return OutputService::error("链接已过期!");
        $from = empty($request->from) ? "other" : $request->from;
        if ($from == "dycard" && $linkMiniappStatus["limit_pv"] == 50000) {
            return OutputService::error("抖音卡片必须开通商家版以上会员!");
        }

        if (in_array($linkMiniappStatus["platfrom_type"], [8,9,11,12])){
            $redirectEngine = Redis::get("redirect_engine");
            if ($redirectEngine == "qrcode") return OutputService::error("生成链接异常");
            // if (in_array($request->city,["南京市","深圳市","长沙市"])) $redirectEngine = "kefu";
            if ($redirectEngine == "kefu" && $linkMiniappStatus["miniapp_status"] == 2) {
                $urlscheme = KefuService::getKefuLink($links_id,$record_id);
                return OutputService::success("SUCCESS",["urlscheme"=>$urlscheme]);
            }
        }
        if ($linkMiniappStatus["miniapp_status"] == 3) {
            $urlscheme = KefuService::getKefuLink($links_id,$record_id);
            return OutputService::success("SUCCESS",["urlscheme"=>$urlscheme]);
        }

        // 获取小程序以及Token
        $miniapp = LinkapiService::getLinkMiniapp($linkMiniappStatus["miniapp_status"],$linkMiniappStatus["limit_pv"],$request->appid,$request);
        if ($miniapp["status"] == "error") return OutputService::error($miniapp["msg"]);
        // 重新加载小程序路径
        $pathquery = LinkapiService::getLinkMiniPath($request,$miniapp["version"]);
        // 生成Scheme
        $generate = MiniappService::urlSchemeCreat($miniapp["access_token"],$request->path,$pathquery);
        if ($generate["status"] == "error") {
            // 生产Scheme错误处理
            LinkapiService::getSchemeError($generate,$miniapp["appid"],$linkMiniappStatus["miniapp_type"]);
            return OutputService::error($generate["msg"]);
        }
        return OutputService::success("SUCCESS",["urlscheme"=>$generate["urlscheme"]]);
    }

    public function urlSchemeSample(Request $request)
    {
        $links_id = $request->links_id;
        $record_id = $request->record_id;
        // 获取外链当前是否为公用
        $linkMiniappStatus = Cache::get("links_card_".$links_id);
        if(empty($linkMiniappStatus)) {
            $linksInfo = Linkslists::getLinkMiniappStatus($links_id);
            if (empty($linksInfo)) return OutputService::error("链接不存在!");
            if (in_array($linksInfo->platfrom_type, [1,13])) {
                $linkMsg = Linkslists::linksListMsg($links_id);
                $msg = $linkMsg->msg;
            } else {
                $msg = "";
            }            
            $linkMiniappStatus = ["miniapp_status"=>$linksInfo->miniapp_status,"platfrom_type"=>$linksInfo->platfrom_type,"miniapp_type"=>$linksInfo->miniapp_type,"appid"=>$linksInfo->appid,"end_time"=>$linksInfo->end_time,"limit_pv"=>$linksInfo->limit_pv,"path"=>$linksInfo->path,"msg"=>$msg];
            // 每次调用缓存2小时
            Cache::put("links_card_".$links_id, $linkMiniappStatus, 7200);
        }
        if ($linkMiniappStatus["end_time"] <= time()) return OutputService::error("链接已过期!");
        if (in_array($linkMiniappStatus["platfrom_type"], [8,9,11,12])){
            $redirectEngine = Redis::get("redirect_engine");
            if ($redirectEngine == "kefu") {
                $urlscheme = KefuService::getKefuLink($links_id,$record_id);
                return OutputService::success("SUCCESS",["urlscheme"=>$urlscheme]);
            }
        }
        if ($linkMiniappStatus["miniapp_status"] == 3) {
            $urlscheme = KefuService::getKefuLink($links_id,$record_id);
            return OutputService::success("SUCCESS",["urlscheme"=>$urlscheme]);
        }
        // 获取小程序以及Token
        $miniapp = LinkapiService::getLinkMiniapp($linkMiniappStatus["miniapp_status"],$linkMiniappStatus["limit_pv"],$linkMiniappStatus["appid"],$request);
        if ($miniapp["status"] == "error") return OutputService::error($miniapp["msg"]);
        // 重新加载小程序路径
        $pathParamas = LinkapiService::getSampleLinkMiniPath($request,$linkMiniappStatus);

        $generate = MiniappService::urlSchemeCreat($miniapp["access_token"],$pathParamas["path"],$pathParamas["query"]);
        if ($generate["status"] == "error") {
            // 生产Scheme错误处理
            LinkapiService::getSchemeError($generate,$miniapp["appid"],$request->miniapp_type);
            return OutputService::error($generate["msg"]);
        }
        return OutputService::success("SUCCESS",["urlscheme"=>$generate["urlscheme"]]);
    }

    public function linkWebStatistic(Request $request)
    {
        try {
            $links_id = $request->links_id;
            $record_id = $request->record_id;
            if (empty($record_id)) {
                // 老版本升级兼容，后续可以删除
                $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
                $record_id = (date("m",time())%4).substr(md5($ip),0,31);
                // $linkList = Linkslists::getLinkSample($links_id);
                // HtmlossService::uploadHtml($linkList->links_id,$linkList->created_at);
                // Log::info("linkWebStatistic-------1");
                // Log::info($links_id);
                // Log::info("linkWebStatistic-------1");
            }
            if (empty($links_id) || $links_id == "undefined") return OutputService::error("Error");
            if(strpos($links_id,"'") !== false || strpos($links_id,'"') !== false || mb_strlen($links_id) > 32) return OutputService::error("Error");

            // 判断是否有CDN
            $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
            $code = empty($request->code) ? "" : $request->code;

            // 根据IP获取城市信息
            $ipinfo = IpService::getAddressByIp($ip);
            $province = mb_substr($ipinfo["province"], 0, 9);
            $city = mb_substr($ipinfo["city"], 0, 14);
            // 增加页面访问PV
            Redis::hincrby('page_view_'.date("Ymd",time()),$links_id,1);
            $web_time = time();
            // 添加网页访问记录
            $linkRecord = new Linksrecord(["tbnum"=>$record_id[0]]);
            $linkRecord->creatLinkRecordWeb($record_id,$links_id,$province,$city,$request->system,$request->device,$request->browser,$ip,$code,$web_time);
            return OutputService::success("SUCCESS");
        } catch (Exception $e) {
            Log::info("linkWebStatistic-------");
            Log::info($request->all());
            Log::info("linkWebStatistic-------");
        }
    }

    public function linkMiniStatistic(Request $request)
    {
        $linksId = explode("_",$request->links_id);
        $links_id = $linksId[0];
        $record_id = $request->record_id;
        if (empty($links_id) || $links_id == "undefined") return OutputService::error("Error");
        $today = date("Ymd",time());
        $linkRecord = new Linksrecord(["tbnum"=>$record_id[0]]);

        // 兼容以前的BUG
        $statTime = $request->stat_time;
        if ($request->stat_time == 1) {
            if ($request->jump_type == 1) {
                $mini_version = empty($request->mini_version) ? 0 : $request->mini_version;
                if ($mini_version < 1) {
                    $statTime = 2;
                }
            }
        }
        if ($statTime == 1) {
            // 首次上报数据
            if ($request->jump_type == 1) {
                // 通过Scheme跳转小程序
                if ($request->mini_show_time != 1) {
                    // 增加二维码展示量
                    Redis::hincrby('mini_view_'.$today,$links_id,1);
                }
                if ($request->mini_press_time != 1) {
                    // 增加长按识别展示量
                    Redis::hincrby('mini_activate_'.$today,$links_id,1);
                }
                if ($request->mini_card_time != 1) {
                    // 增加点击名片量
                    Redis::hincrby('mini_card_'.$today,$links_id,1);
                }
                $linkRecord->updateLinkRecordWeb($record_id,$request->mini_open_time,$request->mini_show_time,$request->mini_press_time,$request->mini_card_time,$request->mini_hide_time,$request->qrcodes_id);
            } else {
                // 直接拉起小程序
                Redis::hincrby('mini_direct_'.$today,$links_id,1);
                if ($request->mini_show_time != 1) {
                    // 增加二维码展示量
                    Redis::hincrby('mini_view_'.$today,$links_id,1);
                }
                if ($request->mini_press_time != 1) {
                    // 增加长按识别展示量
                    Redis::hincrby('mini_activate_'.$today,$links_id,1);
                }
                if ($request->mini_card_time != 1) {
                    // 增加点击名片量
                    Redis::hincrby('mini_card_'.$today,$links_id,1);
                }
                $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
                $ipinfo = IpService::getAddressByIp($ip);
                $province = mb_substr($ipinfo["province"], 0, 9);
                $city = mb_substr($ipinfo["city"], 0, 14);
                $system = DeviceService::getSystem($request->vendor);
                $device = DeviceService::getDevices($request->pvendor);
                $browser = 1;
                $linkRecord->creatLinkRecordMini($record_id,$links_id,$province,$city,$system,$device,$browser,$ip,"",$request->mini_open_time,$request->mini_show_time,$request->mini_press_time,$request->mini_card_time,$request->mini_hide_time);
            }
        } else {
            $linkRecordLast = $linkRecord->getLinkRecordDetial($record_id);
            if (empty($linkRecordLast)) {
                // 通过Scheme跳转小程序
                if ($request->mini_show_time != 1) {
                    // 增加二维码展示量
                    Redis::hincrby('mini_view_'.$today,$links_id,1);
                }
                if ($request->mini_press_time != 1) {
                    // 增加长按识别展示量
                    Redis::hincrby('mini_activate_'.$today,$links_id,1);
                }
                if ($request->mini_card_time != 1) {
                    // 增加点击名片量
                    Redis::hincrby('mini_card_'.$today,$links_id,1);
                }
                $linkRecord->creatLinkRecordMini($record_id,$links_id,"","",1,1,1,"","",$request->mini_open_time,$request->mini_show_time,$request->mini_press_time,$request->mini_card_time,$request->mini_hide_time);
            } else {
                $updateStatus = 1;
                if ($linkRecordLast->mini_show_time == 1 && $request->mini_show_time != 1) {
                    // 增加二维码展示量
                    Redis::hincrby('mini_view_'.$today,$links_id,1);
                    $updateStatus = 2;
                }
                if ($linkRecordLast->mini_press_time == 1 && $request->mini_press_time != 1) {
                    // 增加二维码展示量
                    Redis::hincrby('mini_activate_'.$today,$links_id,1);
                    $updateStatus = 2;
                }
                if ($linkRecordLast->mini_card_time == 1 && $request->mini_card_time != 1) {
                    // 增加点击名片量
                    Redis::hincrby('mini_card_'.$today,$links_id,1);
                    $updateStatus = 2;
                }
                if ($updateStatus == 2) {
                    $linkRecordLast->updateLinkRecordWeb($record_id,$request->mini_open_time,$request->mini_show_time,$request->mini_press_time,$request->mini_card_time,$request->mini_hide_time,$request->qrcodes_id);
                }
            }
        }
        return OutputService::success("SUCCESS");
    }
}